package com.ponxu.mb.web.action.admin;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ponxu.mb.model.User;
import com.ponxu.mb.service.UserService;
import com.ponxu.mb.web.action.MiniBlogAction;
import com.ponxu.utils.Lang;
import com.ponxu.web.core.WebContext;

/**
 * 登陆
 * 
 * @author xwz
 */
public class LoginAction extends MiniBlogAction {
	private static final String FTL_LOGIN = "/admin/login.ftl";
	private static final String FTL_LOGIN_OK = "/admin/index";

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		WebContext context = new WebContext(request, response);
		if (context.sessionGet("admin") != null) {
			context.redirect(FTL_LOGIN_OK);
			return null;
		}
		context.put("referer", context.getParameter("referer"));
		return FTL_LOGIN;
	}

	// 登陆
	public String in(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		WebContext context = new WebContext(request, response);
		String username = context.getParameter("mb_username");
		String password = context.getParameter("mb_password");
		String referer = context.getParameter("referer");

		Object admin = null;
		if (Lang.isNotEmpty(username)) {
			admin = UserService.attempLogin(username, Lang.md5(password));
			if (admin instanceof User) {
				// 登陆成功
				context.sessionSet("admin", admin);
				context.redirect(Lang.defaultString(referer, FTL_LOGIN_OK));
				return null;
			}
		}

		// 登陆失败
		context.put("referer", referer);
		context.put("loginMsg", admin);
		return FTL_LOGIN;
	}

	// 退出
	public String out(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		WebContext context = new WebContext(request, response);
		context.sessionRemove("admin");
		context.redirect("/");
		return null;
	}
}